package com.qf.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Controller
public class TestController {

    @RequestMapping("/download")
    public void download(HttpSession session, HttpServletResponse response) throws IOException {
        String realPath = session.getServletContext().getRealPath("/upload");
        File file = new File(realPath,"174c952d-3aa4-402a-ab3f-863807ed2a08-java从入门到精通.png");

        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename=a.jpg");
        //参数1： 输入流（从哪复制）
        //参数2： 输出流（复制到哪）
        IOUtils.copy(new FileInputStream(file),response.getOutputStream());
    }






    /*
    * MultipartFile  接收文件对象
    * */

    @RequestMapping("/upload")
    public String upload(String username, MultipartFile file, HttpSession session) throws IOException {

        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        //最终存储到服务器上的文件: uuid-abc.jpg
        System.out.println(uuid+"-"+originalFilename);

        //获取服务器路径
        String realPath = session.getServletContext().getRealPath("/upload");
        System.out.println(realPath);

        File f = new File(realPath);
        //如果此路径不存在则创建此路径
        if (!f.exists()){
            f.mkdirs();
        }
        //上传文件到服务器
        file.transferTo(new File(f,uuid+"-"+originalFilename));
        return "/success.jsp";
    }
}
